<?php

namespace Sharks\Core\Http;

use InvalidArgumentException;
use Sharks\Core\Support\Base\Argument;
use Sharks\Core\Support\Base\Precondition;
use Sharks\Core\Support\Base\Str;

/**
 * Session 使用
 */
class Session {

    public function __construct() {
        if (!defined('__SHARKS_SYS_SESSION_STARTED')) {
            @session_start();
            define('__SHARKS_SYS_SESSION_STARTED', 1);
        }
    }

    public function get($name, $default = null) {
        if (isset($_SESSION[$name])) {
            return unserialize($_SESSION[$name]);
        }
        return $default;
    }

    public function getOrFail($key) {
        $result = $this->get($key);
        Precondition::checkNotNull($result, '错误的Session参数 %s', $key);
        return $result;
    }

    /**
     * 是否有值
     * @param $name
     * @return bool
     */
    public function has($name) {
        return isset($_SESSION[$name]);
    }

    public function forget($name) {
        $forgetValue = $this->get($name);
        unset($_SESSION[$name]);
        return $forgetValue;
    }

    public function forgetAll() {
        session_destroy();
    }

    public function put($name, $value) {
        $_SESSION[$name] = serialize($value);
    }

    /**
     * 清空全部或某一前辍的session
     * @param null $prefix
     */
    public function clear($prefix = null) {
        if (is_null($prefix)) {
            // 清空session
            session_unset();
        }
        else {
            // 逐个清空该前辍的session
            foreach ($this->all() as $key => $value) {
                if (Str::startsWith($key, $prefix)) {
                    unset($_SESSION[$key]);
                }
            }
        }
    }

    public function all() {
        return $_SESSION;
    }
}